package com.hcinfos.gsoo.ui;

import java.io.File;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.enity.Version;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.json.VersionJson;
import com.hcinfos.gsoo.util.ApkDownloadUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.VersionUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TabHost;
import android.widget.Toast;

public class MainTabActivity extends BaseMenuActivity implements
		OnCheckedChangeListener {

	private TabHost tabHost;
	private Intent homeIntent;
	private Intent nearIntent;
	private Intent diancaiIntent;
	private Intent profileIntent;

	private RadioButton radio_btn_home;
	private RadioButton radio_btn_near;
	private RadioButton radio_btn_diancai;
	private RadioButton radio_btn_profile;

	private SharePreferenceUtil util;
	private LocalActivityManager activityGroup;

	private final int NEW_VERSION = 0x2210;
	private final int OBTAIN_END = NEW_VERSION + 1;
	private final int OBTAIN_FAIL = NEW_VERSION + 2;
	private final int NO_NEW_VERSION = NEW_VERSION + 3;
	private final int GET_VERSION_FAIL = NEW_VERSION + 4;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		util = new SharePreferenceUtil(this, "setting");
		getSlidingMenu().setMode(SlidingMenu.LEFT);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		GsooApplication.sildingMenu = getSlidingMenu();
		setContentView(R.layout.activity_tab_main);
		homeIntent = new Intent(this, RandomNearActivity.class);
		nearIntent = new Intent(this, ListDisplayActivity.class);
		diancaiIntent = new Intent(this, OnlineOrderMainActivity.class);
		profileIntent = new Intent(this, ProfileActivity.class);
		tabHost = (TabHost) findViewById(R.id.tabhost);
		activityGroup = new LocalActivityManager(this, true);
		activityGroup.dispatchCreate(savedInstanceState);
		tabHost.setup(activityGroup);
		tabHost.setCurrentTab(0);
		initRadios();
		setupIntent();
		checkVersion();
	}

	private Version version;

	/**
	 * 版本检查
	 */
	private void checkVersion() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							MainTabActivity.this,
							"http://www.gsoo.com/apps/version.jsp");
					if (result != null) {
						version = VersionJson.getVersionByJson(result);
						if (VersionJson.state == 200) {
							if (version == null)
								return;
							int currentCode = VersionUtil
									.getCurrentLocalVersion(MainTabActivity.this);
							if (version.getVersionCode() > currentCode) {
								Message msg = handler.obtainMessage();
								msg.what = NEW_VERSION;
								handler.sendMessage(msg);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = NO_NEW_VERSION;
								handler.sendMessage(msg);
							}

						}
					} else {
						Message msg = handler.obtainMessage();
						msg.what = GET_VERSION_FAIL;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					LogUtil.e("wxf", "checkVersion=" + e.toString());
					Message msg = handler.obtainMessage();
					msg.what = GET_VERSION_FAIL;
					handler.sendMessage(msg);
				}

			}
		}).start();
	}

	private void initRadios() {

		radio_btn_home = ((RadioButton) findViewById(R.id.radio_btn_home));
		radio_btn_home.setOnCheckedChangeListener(this);
		radio_btn_near = ((RadioButton) findViewById(R.id.radio_btn_near));
		radio_btn_near.setOnCheckedChangeListener(this);
		radio_btn_diancai = ((RadioButton) findViewById(R.id.radio_btn_diancai));
		radio_btn_diancai.setOnCheckedChangeListener(this);
		radio_btn_profile = ((RadioButton) findViewById(R.id.radio_btn_profile));
		radio_btn_profile.setOnCheckedChangeListener(this);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		sendBroadcast(new Intent("com.login.update.action"));
		activityGroup.dispatchResume();
		User user = (User) util.loadObject("user");
		if (user != null) {
			login_tv.setText(user.getUsername() == null ? user.getGgnumber()
					: user.getUsername());
		} else {
			login_tv.setText("未登陆");
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		activityGroup.dispatchPause(true);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_btn_home:
				radio_btn_home
						.setBackgroundResource(R.drawable.new_tab_select_bg);
				radio_btn_near.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_diancai.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_profile.setBackgroundColor(Color.TRANSPARENT);
				this.tabHost.setCurrentTabByTag("home_tab");
				break;
			case R.id.radio_btn_near:
				this.tabHost.setCurrentTabByTag("near_near");
				radio_btn_near
						.setBackgroundResource(R.drawable.new_tab_select_bg);
				radio_btn_home.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_diancai.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_profile.setBackgroundColor(Color.TRANSPARENT);
				break;
			case R.id.radio_btn_diancai:
				this.tabHost.setCurrentTabByTag("diancai_tab");
				radio_btn_diancai
						.setBackgroundResource(R.drawable.new_tab_select_bg);
				radio_btn_home.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_near.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_profile.setBackgroundColor(Color.TRANSPARENT);
				break;
			case R.id.radio_btn_profile:
				this.tabHost.setCurrentTabByTag("profile_tab");
				radio_btn_profile
						.setBackgroundResource(R.drawable.new_tab_select_bg);
				radio_btn_home.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_near.setBackgroundColor(Color.TRANSPARENT);
				radio_btn_diancai.setBackgroundColor(Color.TRANSPARENT);
				break;
			}
		}
	}

	private void setupIntent() {
		TabHost localTabHost = this.tabHost;
		localTabHost.addTab(buildTabSpec("home_tab", R.string.home,
				R.drawable.new_home_icon, this.diancaiIntent));

		localTabHost.addTab(buildTabSpec("near_near", R.string.near,
				R.drawable.new_lbs_icon, this.nearIntent));

		localTabHost.addTab(buildTabSpec("diancai_tab", R.string.diancai,
				R.drawable.new_diancai_icon, this.homeIntent));

		localTabHost.addTab(buildTabSpec("profile_tab", R.string.profile,
				R.drawable.new_profile_icon, this.profileIntent));
	}

	private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon,
			final Intent content) {
		return this.tabHost
				.newTabSpec(tag)
				.setIndicator(getString(resLabel),
						getResources().getDrawable(resIcon))
				.setContent(content);
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case GET_VERSION_FAIL:
				Toast.makeText(MainTabActivity.this, "获取失败", 500).show();
				break;
			case NEW_VERSION:
				DialogUtil.versionDialog(MainTabActivity.this,
						version.getVersionDes(), new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								try {
									ApkDownloadUtil util = new ApkDownloadUtil(
											getApplicationContext(),
											handler,
											Urls.COMMON_URL
													+ version.getApkUrl(),
											String.valueOf(getText(R.string.app_name)
													+ "_"
													+ VersionUtil
															.getVersionName(MainTabActivity.this)));
									util.start();
								} catch (Exception e) {
								}
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "升级", "取消");
				break;
			case ApkDownloadUtil.MSG_DOWNING:
				Toast.makeText(getApplicationContext(), R.string.downloadStart,
						Toast.LENGTH_LONG).show();
				break;
			case ApkDownloadUtil.MSG_FINISH:
				String path = (String) msg.obj;
				installAPK(path);
				break;
			case ApkDownloadUtil.MSG_FAILURE:
				Toast.makeText(getApplicationContext(),
						R.string.downloadFailure, Toast.LENGTH_LONG).show();
				break;
			}

		};
	};

	private void installAPK(String path) {

		Uri uri = Uri.fromFile(new File(path));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
	}

}
